import { PublicService } from '@/utils/public';
import { NativeService } from '@/utils/native-service';
import { isPlatform } from '@ionic/vue';
import { gcj_encrypt, bd_decrypt } from '@/utils/ths-location'
const publicService: PublicService = PublicService.getInstance();
const nativeService = new NativeService();
export class NavigationService { 
  // 当前我的位置（起点位置）
  private sLocation: any = {
    sLat: '',
    sLon: '',
    sName: '我的位置'
  };
  // 目的地 (终点位置)
  private dLocation: any = {
    dLat: '',
    dLon: '',
    dName: ''
  };

  /**
   * 开启导航操作
   * @param dLoc 导航终点位置信息
   */
   beginNav(dLoc: any) {
    this.dLocation = dLoc;
    if (!this.dLocation.dLat || !this.dLocation.dLon){
      publicService.thsToast('暂未提供经纬度无法导航');
      return;
    }
    nativeService.startLoc().then((res) => {
      this.sLocation.lat = res.lat;
      this.sLocation.sLon = res.lng;
      this.checkApp();
    });
   }
  
  /**
   * 检查设备是否安装高德地图或百度地图
   */
  async checkApp() {
    let gaoDeapp: any;
    let baiDuapp: any;
    // const platform = await nativeService.getDeviceInfo();
    if (isPlatform('ios')) {
      gaoDeapp = 'iosamap://'; // 高德地图
      baiDuapp = 'baidumap://'; // 百度地图
    } else if (isPlatform('android')) {
      gaoDeapp = 'com.autonavi.minimap';
      baiDuapp = 'com.baidu.BaiduMap';
    }

    console.log(gaoDeapp);
    // nativeService.checkAppAvailability(gaoDeapp)
    nativeService.checkAppAvailability(gaoDeapp).then((res) => {
      this.openApp('gaode');
    }).catch((error) => {
      console.log('gaode', error)
      nativeService.checkAppAvailability(baiDuapp).then((res) => {
        this.openApp('baidu');
      }).catch((error) => {
        console.log('baidu', error)
        publicService.thsToast('请先下载百度或高德地图');
      })
    });
  }

  /**
   * 打开第三方app
   * @param data gaode 高德地图 baidu百度地图
   */
   openApp(data: any) {
    let appPackage;
    let appUri;
    // 当前位置是WGS-84坐标系
    // 高德地图上需要将其他坐标系的经纬度转换为GCJ-02坐标系的经纬度
    const sLon_gcj = gcj_encrypt(this.sLocation.sLat, this.sLocation.sLon).lon;
    const sLat_gcj = gcj_encrypt(this.sLocation.sLat, this.sLocation.sLon).lat;
    const dLon_gcj = bd_decrypt(this.dLocation.dLat, this.dLocation.dLon).lon;
    const dLat_gcj = bd_decrypt(this.dLocation.dLat, this.dLocation.dLon).lat;

    if (isPlatform('android')) {
      if (data === 'gaode') {
        appPackage = 'com.autonavi.minimap';
        if (this.sLocation.sLat && this.sLocation.sLon) {
          appUri = 'amapuri://route/plan/?&slat=' + sLat_gcj + '&slon=' + sLon_gcj + '&sname=我的位置&dlat=' +
          this.dLocation.dLat + '&dlon=' + this.dLocation.dLon + '&dname=' + this.dLocation.dName + '&dev=0&t=0'; // 选择路径规划然后导航
        } else {
          appUri = 'amapuri://route/plan/?&dlat=' +
          this.dLocation.dLat + '&dlon=' + this.dLocation.dLon + '&dname=' + this.dLocation.dName + '&dev=0&t=0'; // 选择路径规划然后导航
        }
        // appUri = 'amapuri://route/plan/?&slat=' + sLat_gcj + '&slon=' + sLon_gcj + '&sname=我的位置&dlat=' +
        //   this.dLocation.dLat + '&dlon=' + this.dLocation.dLon + '&dname=' + this.dLocation.dName + '&dev=0&t=0'; // 选择路径规划然后导航
      } else {
        appPackage = 'com.baidu.BaiduMap';
        if (!this.dLocation.dLat || this.dLocation.dLat === '--') {
          appUri = 'baidumap://map/direction?origin=我的位置&destination=' + this.dLocation.dName + '&coord_type=gcj02&mode=driving';
        } else {
          appUri = 'baidumap://map/direction?origin=我的位置&destination=name:' + this.dLocation.dName + '|latlng:' +
            this.dLocation.dLat + ',' + this.dLocation.dLon + '|addr:' + this.dLocation.dName + '&coord_type=gcj02&mode=driving';
        }
      }
      const sApp = (window as any).startApp.set({// 跳转对应APP
        action: 'ACTION_VIEW',
        category: 'CATEGORY_DEFAULT',
        type: 'text/css',
        package: appPackage,
        uri: appUri,
        flags: ['FLAG_ACTIVITY_CLEAR_TOP', 'FLAG_ACTIVITY_CLEAR_TASK'],
        intentstart: 'startActivity',
      }, { /* extras */
        EXTRA_STREAM: 'extraValue1',
        extraKey2: 'extraValue2'
      });
      sApp.start(() => { // 跳转成功
        // alert('OK');
      }, (error: any) => { // 失败
        // alert(error);
      });
    } else if (isPlatform('ios')) {
      if (data === 'gaode') {
        appUri = 'iosamap://path?sourceApplication=applicationName&sid=BGVIS1&slat=&slon=&sname=&did=BGVIS2&dlat='
          + dLat_gcj + '&dlon=' + dLon_gcj + '&dname=' + encodeURI(this.dLocation.dName) + '&dev=0&t=0'; // 选择路径规划然后导航
      } else {
        appUri = 'baidumap://map/direction?origin=' + sLat_gcj + ',' + sLon_gcj + '&destination=' +
          dLat_gcj + ',' + dLon_gcj + '&coord_type=gcj02&mode=driving&src=ios.baidu.openAPIdemo';
      }
      const sApp = (window as any).startApp.set(appUri);
      sApp.start(() => {
        //  alert('OK');
      }, (error: any) => {
        // alert(error);
      });
    }
  }
}